package com.xiaohua.xiaohuamall.product.service.impl;

import com.mysql.cj.util.StringUtils;
import com.xiaohua.xiaohuamall.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohua.common.utils.PageUtils;
import com.xiaohua.common.utils.Query;

import com.xiaohua.xiaohuamall.product.dao.BrandDao;
import com.xiaohua.xiaohuamall.product.entity.BrandEntity;
import com.xiaohua.xiaohuamall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        if (!StringUtils.isNullOrEmpty((String) params.get("key"))){
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    new QueryWrapper<BrandEntity>().like("name",params.get("key")).or().eq("brand_id",params.get("key"))
            );
//            page.setTotal(page.getRecords().size());
            return new PageUtils(page);
        }else{
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    new QueryWrapper<BrandEntity>()
            );
//            page.setTotal(page.getRecords().size());
            return new PageUtils(page);
        }
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        //保证冗余字段的数据一致
        this.updateById(brand);
        if (!StringUtils.isNullOrEmpty(brand.getName())){
            //同步更新其他关联表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            //TODO 更新其他关联
        }
    }

}